/**
 * Created by xinhuang on 15/4/18.
 */
(function () {
  'use strict';
  angular.module('directives.customActivity')
    .directive('aquarius', aquarius);

  function aquarius($interval) {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        width: '@',
        class: '@',
        style: '@',
        height: '@',
        percentage: '=',
        scolor: '=',
        text: '=',
        fontcolor: '='
      },
      template: '<canvas class="{{class}}" style="{{style}}"></canvas>',
      link: postLink
    };

    function postLink(scope, element) {
      var canvas = element[0];
      canvas.width = scope.width;
      canvas.height = scope.height;
      var ctx = canvas.getContext('2d');
      var myconvas = {
        scolor: scope.scolor == undefined ? 'rgb(0,222,255)' : scope.scolor, //水颜色
        fontcolor: scope.fontcolor == undefined ? '#000000' : scope.fontcolor, //字颜色
        step: 0
      };

      scope.$watch('percentage', function(){
        myconvas.scolor = scope.scolor == undefined ? 'rgb(0,222,255)' : scope.scolor; //水颜色
        myconvas.fontcolor = scope.fontcolor == undefined ? '#000000' : scope.fontcolor; //字颜色
        var gd = (canvas.height - canvas.height * (parseInt(scope.percentage) / 100)) * 10 + 2;
        var text = scope.text == undefined ? '0' : scope.text;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = myconvas.scolor;
        myconvas.step++;
        var angle = myconvas.step * Math.PI / 180;
        var deltaHeight = Math.sin(angle) * 2;
        var deltaHeightRight = Math.cos(angle) * 2;
        ctx.beginPath();
        ctx.moveTo(0, gd + deltaHeight);
        ctx.bezierCurveTo(canvas.width / 2 + (deltaHeightRight * 40), gd + deltaHeight, canvas.width / 2 + (deltaHeightRight * 40), gd + deltaHeightRight, canvas.width, gd + deltaHeightRight);
        ctx.lineTo(canvas.width, canvas.height);
        ctx.lineTo(0, canvas.height);
        ctx.lineTo(0, canvas.height / 2 + deltaHeight);
        ctx.closePath();
        ctx.fill();
        ctx.fillStyle = myconvas.fontcolor;
        ctx.font = '25px 微软雅黑';
        var ztk = (text.length * 16) / 2;
        ctx.fillText(text, (canvas.width + 8) / 2 - ztk, (canvas.height + 20) / 2);
      },true);
    }
  }
})();